package com.ydm.controller;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ydm.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user/login")
    public Map<String,Object> login(User user){
        Map<String,Object> map = new HashMap<>();
        try{
            User userDB = userService.login(user);
            Map<String,String> payload = new HashMap<>();
            payload.put("id",userDB.getId);
            payload.put("name",userDB.getUsername());

            //生成jwt令牌
            String token = JWTUtil.getToken(payload);
            map.put("state",true);
            map.put("msg","认证成功");
            map.put("token",token);
        }catch (Exception e){
            map.put("state",false);
            map.put("msg",e.fillInStackTrace());
        }
        return map;
    }

    @PostMapping("/user/test")
    public Map<String,Object> test(String token){
        Map<String,Object> map = new HashMap<>();
        // 处理自己的业务逻辑

//        try {
//            DecodedJWT verify = JWTUtil.verifyToken(token);
//            map.put("state",true);
//            map.put("msg","请求成功");
//            return map;
//        }catch (SignatureVerificationException e){
//            e.printStackTrace();
//            map.put("msg","无效签名");
//        }catch (TokenExpiredException e){
//            e.printStackTrace();
//            map.put("msg","token过期");
//        }catch (AlgorithmMismatchException e){
//            e.printStackTrace();
//            map.put("msg","算法不一致");
//        }catch (Exception e){
//            e.printStackTrace();
//            map.put("msg","token无效");
//        }
//        map.put("state",false);
        return map;
    }
}
